﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using APH.Parl2.Shared.Contracts;
using APH.Parl2.Shared.XML;
using System.ServiceModel;
using System.Xml;
using System.Xml.Schema;
using System.IO;
using System.Reflection;

namespace APH.Parl2.Business.Publishing
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, UseSynchronizationContext = false)]
    public class ValidationEngine : IValidationEngine
    {
        [OperationBehavior(TransactionScopeRequired = true)]
        public void Validate(TranslatedDocumentData documentData)
        {
            string assemblyDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);

            if (documentData != null)
                ValidateDocBook(documentData.DocumentXml, Path.Combine(assemblyDir, @"Xsd\docbook.xsd"));

        }

        static public void ValidateDocBook(string xml, string xsdPath)
        {
            XmlReaderSettings booksSettings = new XmlReaderSettings();
            booksSettings.Schemas.Add("http://docbook.org/ns/docbook", xsdPath);
            booksSettings.ValidationType = ValidationType.Schema;
            booksSettings.ValidationEventHandler += new ValidationEventHandler(MyValidationEventHandler);

            var reader = new StringReader(xml);
            XmlReader docBook = XmlReader.Create(reader, booksSettings);

            while (docBook.Read()) { }

        }

        static void MyValidationEventHandler(object sender, ValidationEventArgs e)
        {
            if (e.Severity == XmlSeverityType.Warning)
            {
                //Ignore warnings
            }
            else if (e.Severity == XmlSeverityType.Error)
            {
                throw new XmlSchemaValidationException();
            }
        }
    }
}
